//
//  AddNewCarSectionViewController.m
//  Collection
//
//  Created by satya on 25/12/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//



#define SCROLLVIEW_CONTENT_HEIGHT 460
#define SCROLLVIEW_CONTENT_WIDTH  320

#import "AddNewCarSectionViewController.h"
#import "dbFunctions.h"
#import "DropDownView.h"

CGFloat animatedDistance;
static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
static const CGFloat MINIMUM_SCROLL_FRACTION = 0.2;
static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 215;
static const CGFloat LANDSCAPE_KEYBOARD_HEIGHT = 162;
//anyView has been defined for different kind of views to avoid keyboard when entering data in textfield.
UIView *anyView;


@implementation AddNewCarSectionViewController
@synthesize sender,selector,imgPicker,dDownList;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark -
#pragma mark DropDownViewDelegate

-(void)dropDownCellSelected:(NSInteger)returnIndex{
   
    dbFunctions *db = [[dbFunctions alloc]init];
    [btnCarSecton setTitle:[[db getPDF] objectAtIndex:returnIndex] forState:UIControlStateNormal];
   // driverNameBtn_.tag = returnIndex;
    
    
}

#pragma mark -
#pragma mark TextField Delegates


-(BOOL)textFieldShouldReturn:(UITextField *)txtField{
    [txtField resignFirstResponder];
    return YES;
}

-(BOOL) textFieldShouldBeginEditing:(UITextField*)textField {
	return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
		anyView = self.view;
	
	
	
	
 	CGRect textFieldRect = [anyView.window convertRect:textField.bounds fromView:textField];
 	CGRect viewRect =
 	[anyView.window convertRect:self.view.bounds fromView:self.view];
 	CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;
 	CGFloat numerator =
 	midline - viewRect.origin.y
 	- MINIMUM_SCROLL_FRACTION * viewRect.size.height;
 	CGFloat denominator =
 	(MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION)
 	* viewRect.size.height;
 	CGFloat heightFraction = numerator / denominator;
 	if (heightFraction < 0.0)
 	{ 
		heightFraction = 0.0;
 	}
 	else if (heightFraction > 1.0)
 	{
		heightFraction = 1.0;
 	}
 	UIInterfaceOrientation orientation =
 	
	[[UIApplication sharedApplication] statusBarOrientation];
 	if (orientation == UIInterfaceOrientationPortrait ||
		orientation == UIInterfaceOrientationPortraitUpsideDown)
 	{
		animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
 	}
 	else
 	{
		animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction);
 	}
	
 	CGRect viewFrame = self.view.frame;
 	viewFrame.origin.y -= animatedDistance;
	
 	[UIView beginAnimations:nil context:NULL];
 	[UIView setAnimationBeginsFromCurrentState:YES];
 	[UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
 	[anyView setFrame:viewFrame];
 	[UIView commitAnimations];	
	
}


- (void)textFieldDidEndEditing:(UITextField *)textField
{
	
	CGRect viewFrame = self.view.frame;
	viewFrame.origin.y += animatedDistance;
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
	[UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
	[anyView setFrame:viewFrame];
	[UIView commitAnimations];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"Add CarSection";
    // Do any additional setup after loading the view from its nib.
}

-(IBAction)selectCarSecton:(UIButton*)select
{
    dbFunctions *db = [[dbFunctions alloc]init];
    
    dDownList = [[DropDownView alloc] initWithArrayData:[db getPDF] cellHeight:30 heightTableView:180 paddingTop:0 paddingLeft:-7 paddingRight:-13 refView:select animation:BLENDIN openAnimationDuration:.5 closeAnimationDuration:.5];
	//[driverNameBtn_ addTarget:self action:@selector(actionButtonClick) forControlEvents:UIControlEventTouchUpInside];
	dDownList.delegate = self;
    [dDownList openAnimation];
	
    [self.view addSubview:dDownList.view];
    [db release];

}

-(IBAction)dismissMe:(UIBarButtonItem*)btnSender;
{
    
    if (btnSender.tag==1001) {
        [sender performSelector:(selector)];
    }
    else {
         dbFunctions *add = [[dbFunctions alloc]init];
        
        [add addNewSection:btnCarSecton.titleLabel.text accidentDamage:txtAccDam.text nonRelatedAccident:txtnonReleted.text privateQArea:txtPrivQArea.text];
       
        [add release];
        
        NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString *pngFilePath = [NSString stringWithFormat:@"%@/%@",docDir,btnCarSecton.titleLabel.text];
        NSLog(@"...... %@",pngFilePath);
        
        NSData *imgData = [NSData dataWithData:UIImageJPEGRepresentation(pickedImage, 0.0)];
        
        [imgData writeToFile:pngFilePath atomically:YES];
        
        [imgPicker release];
        [sender performSelector:(selector)];


    }
    

}

-(IBAction)pickImageClick;
{
UIActionSheet *actiosheet = [[UIActionSheet alloc]initWithTitle:@"SELECT" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"Cancel" otherButtonTitles:@"Take New Picture",@"Go To Photo Album",nil];
actiosheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;

[actiosheet showInView:self.view];
[actiosheet release];

}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
	imgPicker = [[UIImagePickerController alloc] init];
	imgPicker.delegate = self;
	if (buttonIndex == 1) {
		//self.label.text = @"Other Button 1 Clicked";
		if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
			imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
			[self presentModalViewController:imgPicker animated:YES];
		}
		else {
			UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Currently, Your device does not support camera. " delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
			alert.opaque = YES;
			[alert show];
			[alert release];
		}
		
	} 
	else if (buttonIndex == 2) {
		//self.label.text = @"Other Button 2 Clicked";
		imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
		[self presentModalViewController:imgPicker animated:YES];
	}
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
	UIImage *im=[info objectForKey:@"UIImagePickerControllerOriginalImage"];
	UIGraphicsBeginImageContext( CGSizeMake(im.size.width/4 ,im.size.height/4) );
[[info objectForKey:@"UIImagePickerControllerOriginalImage"] drawInRect:CGRectMake(0,0,im.size.width/4 ,im.size.height/4)];
	pickedImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	[btnImage setBackgroundImage:pickedImage forState:UIControlStateNormal];
    [picker dismissModalViewControllerAnimated:YES];
}



- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
